package com.goldman.aplt.util;

import com.goldman.aplt.base.constant.ApConstants;
import com.goldman.aplt.base.exception.BusiErrorCode;
import com.goldman.aplt.base.type.BaseEnumType;
import com.goldman.aplt.base.type.ComMessage;
import com.goldman.aplt.service.parameter.AppSystemParameterService;
import com.goldman.base.common.sys.exception.BusinessException;
import com.goldman.http.common.s2s.S2SOption;
import com.goldman.http.common.s2s.S2SResponse;
import com.goldman.http.common.s2s.model.HeaderConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.Map;
import java.util.UUID;

/**
 * @description：发送邮件和短信
 * @author： chenxiangxiang
 * @create： 2024/1/24 20:52
 */
@Component
@Slf4j
public class MessageUtil {

    @Autowired
    private AppSystemParameterService appSystemParameterService;

    public String getMessageTypeUrl(BaseEnumType.E_MESSAGE_TYPE type) {
        String url = "";
        if (type == BaseEnumType.E_MESSAGE_TYPE.SHORT_MESSAGE) {
            url = appSystemParameterService.getValue("mdut", "sendShortMessUrl");
        } else if (type == BaseEnumType.E_MESSAGE_TYPE.EMAIL) {
            url = appSystemParameterService.getValue("mdut", "sendEmailUrl");
        } else if (type == BaseEnumType.E_MESSAGE_TYPE.OTP_SHORT_MESSAGE) {
            url = appSystemParameterService.getValue("mdut", "sendOtpShortMessUrl");
        } else if (type == BaseEnumType.E_MESSAGE_TYPE.OTP_EMAIL) {
            url = appSystemParameterService.getValue("mdut", "sendOtpEmailUrl");
        } else {
            url = appSystemParameterService.getValue("mdut", "sendOtpVoiceUrl");
        }

        return url;
    }

    /**
     * 收费
     *
     * @param type
     * @param scene
     * @param emailOrPhone
     * @param extendedFields
     * @param acctNo
     * @param custNo
     */
    public void sendMessageFee(BaseEnumType.E_MESSAGE_TYPE type, String scene, String emailOrPhone,
                               Map<String, Object> extendedFields, Map<String, Object> attachments, String acctNo, String custNo) {
        sendMessageComm(type, scene, emailOrPhone, extendedFields, attachments, acctNo, custNo, true);
    }

    /**
     * 不收费
     *
     * @param type
     * @param scene
     * @param emailOrPhone
     * @param extendedFields
     */
    public void sendMessageNoFee(BaseEnumType.E_MESSAGE_TYPE type, String scene, String emailOrPhone,
                                 Map<String, Object> extendedFields) {
        sendMessageComm(type, scene, emailOrPhone, extendedFields, null,"", "", false);
    }

    /**
     * 不收费, 有附件
     *
     * @param type
     * @param scene
     * @param emailOrPhone
     * @param extendedFields
     */
    public void sendMessageNoFeeAttchements(BaseEnumType.E_MESSAGE_TYPE type, String scene, String emailOrPhone,
                                 Map<String, Object> extendedFields, Map<String, Object> attachments) {
        sendMessageComm(type, scene, emailOrPhone, extendedFields, attachments,"", "", false);
    }

    /**
     * 发送邮件和短信不收费
     *
     * @param type
     * @param scene
     * @param emailOrPhone
     * @param extendedFields
     */
    private void sendMessageComm(BaseEnumType.E_MESSAGE_TYPE type, String scene, String emailOrPhone,
                                 Map<String, Object> extendedFields, Map<String, Object> attachments,
                                 String acctNo, String custNo, boolean isFee) {
        try {
            String url = getMessageTypeUrl(type);

            //构建邮件内容
            ComMessage.EmailReq req = new ComMessage.EmailReq();
            req.setTimestamp(System.currentTimeMillis() + "");
            req.setCountry(ApConstants.BASE_COUNTRY_NG);
            req.setRecipient(emailOrPhone);
            req.setClientNo("0");
            req.setAcctNo("0");
            req.setSubAcctNo("0");

            if (isFee) {
                req.setClientNo(custNo);
                if (CommUtil.isNotNull(acctNo)) {
                    req.setAcctNo(acctNo);
                    req.setSubAcctNo("1");
                }
            }

            if (type == BaseEnumType.E_MESSAGE_TYPE.OTP_SHORT_MESSAGE
                    || type == BaseEnumType.E_MESSAGE_TYPE.OTP_EMAIL
                    || type == BaseEnumType.E_MESSAGE_TYPE.OTP_VOICE) {
                req.setOtpDigits("4");
                req.setLifespan("");
            }

            req.setSource("B");
            req.setScene(scene);
            req.setMsgId(DigestUtils.md5DigestAsHex((req.getTimestamp() + req.getScene()).getBytes()));
            if (CommUtil.isNotNull(extendedFields)) {
                req.setExtendedFields(extendedFields);
            }

            if (CommUtil.isNotNull(attachments)) {
                req.setAttachments(attachments);
            }

            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            String clientIp = "";
            String deviceId = "";
            if (CommUtil.isNull(attributes)) {
                clientIp = InetAddress.getLocalHost().getHostAddress();
                deviceId = "JOB" + UUID.randomUUID();
            } else {
                HttpServletRequest request = attributes.getRequest();
                clientIp = NetUtil.getClientIP(request);
                deviceId = request.getHeader(HeaderConstants.DEVICE_ID_HEADER);
            }

            Map<String, String> headerMap = new HashedMap();
            headerMap.put("X-Request-Id", UUID.randomUUID().toString());
            headerMap.put("Client-Ip", clientIp);
            headerMap.put("Device-Id", deviceId);
            headerMap.put("Phone", req.getRecipient());
            S2SOption s2SOption = S2SOption.builder()
                    .contentType(S2SOption.ContentType.JSON)
                    .headers(headerMap)
                    .build();

            log.info(String.format("start send message scene = %s , emailOrPhone = %s", scene, emailOrPhone));
            S2SResponse<String> s2SResponse = HttpUtil.post(url, new ComMessage.RequestData<>(req), s2SOption);
            if (s2SResponse.isHTTPSuccess()) {
                return;
            }

        } catch (Exception e) {
            log.error("MessageUtil exception", e);
        }

        //throw new BusinessException(BusiErrorCode.SYS_ERROR);
    }
}
